// 生成一个随机四位数
function randomNum() {
    let num = Math.floor(Math.random()*10000) + '';
    if(num<10){
        return '000'+ num
    }else if(num<100){
        return '00'+ num
    }else if(num<1000) {
        return '0'+ num
    }else{return num}
}

class Map {
    constructor() {
        // 房间里的人数
        this.peopleNum = 0
        this.clients = new Set()
        // 房间里用户的阵营  0:红方 1：黑方 2:没有人或有两人
        this.clientCamp = 2
        this.init()
    }
    init() {
        this.mapID = randomNum()
    }
    // 加入对战
    add(client) {
        this.clients.add(client)
        this.peopleNum++
        if(this.peopleNum ==0 || this.peopleNum ==2) {
            this.clientCamp = 2
        }else{
            this.clientCamp = client.camp
        }
    }
}
class Client {
    constructor(id, name, camp) {
        this.id = id
        this.name = name
        this.camp = camp
    }
}

class ManageMap {
    constructor() {
        this._entrys = new Array()
    }
    put(client) {
        // 如果没有待需求对战的房间，就直接加入一个房间
        if(this._entrys.length === 0) {
            // 创建一个房间
            let mapObj = new Map();
            mapObj.add(client)
            this.add(mapObj)
            return mapObj.mapID
        }
        // 找到对应的房间
        let map = this._entrys.find((item)=>{
            if(client.camp ===0) {
                return item.clientCamp === 1
            }else{
                return item.clientCamp === 0
            }
        })
        if(!map) {
            // 创建一个房间
            let mapObj = new Map();
            mapObj.add(client)
            this.add(mapObj)
            return mapObj.mapID
        }else{
            map.add(client)
            return map.mapID
        }
    }
    add(mapObj) {
        this._entrys.push(mapObj)
    }
}

// (function(){
//     var managemap = new ManageMap()
//     setTimeout(()=> {
//         var client1 = new Client(1, 'wsq', 0);
//         managemap.put(client1)
//         console.log(managemap)
//     },5000)
//     setTimeout(()=> {
//         var client2 = new Client(2, 'pxh', 0);
//         managemap.put(client2)
//         console.log(managemap)
//     },10000)
//     setTimeout(()=> {
//         var client3 = new Client(3, 'wsg', 1);
//         managemap.put(client3)
//         console.log(managemap)
//     },15000)
    
    
// })()

module.exports = { Client, ManageMap }